<template>
  <keep-alive>
    <a-card :bordered="false">
      <!-- 查询区域 -->
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="序列号">
                <a-input placeholder="请输入序列号" @keyup.enter="searchQuery"
                         v-model="queryParam.unitsn"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a-button type="primary" @click="openRework" icon="highlight" v-has="'barcodeTrace:add'"
                        style="margin-left: 8px;background-color: #c27e19;border-color: #c27e19">不良录入</a-button>
              <a-button type="primary" @click="openRelease" icon="interation" v-has="'barcodeTrace:add'"
                        style="margin-left: 8px;background-color: #19c227;border-color: #24d032">恢复</a-button>
              <a-button type="primary" @click="openAbnormal" icon="warning" v-if="isAbnormal" v-has="'barcodeTrace:add'"
                        style="margin-left: 8px;background-color: #e02020;border-color: #e02020">异常录入</a-button>
              <a-button type="primary" @click="openDataSync" icon="cloud-download"  v-has="'barcodeTrace:add'"
                        style="margin-left: 8px;background-color: #589f7e;border-color: #589f7e">数据同步</a-button>
            </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <div>
        <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
          <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a
          style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
          <a style="margin-left: 24px" @click="onClearSelected">清空</a>
        </div>

        <a-table
          ref="table"
          size="middle"
          bordered
          rowKey="federationId"
          class="j-table-force-nowrap"
          :scroll="{x:true}"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :loading="loading"
          :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type:'radio'}"
          :customRow="clickThenSelect"
          @change="handleTableChange">
          <template slot="lotno" slot-scope="text">
            <a style="color:blue" @click="clickLotNo(text)">{{ text }}</a>
          </template>
          <template slot="boxCode" slot-scope="text">
            <a style="color:blue" @click="clickLotNo(text)">{{ text }}</a>
          </template>
          <template slot="htmlSlot" slot-scope="text">
            <div v-html="text"></div>
          </template>
<!--          <template slot="imgSlot" slot-scope="text,record">-->
<!--            <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>-->
<!--&lt;!&ndash;            <a-image&ndash;&gt;-->
<!--&lt;!&ndash;              :width="200"&ndash;&gt;-->
<!--&lt;!&ndash;              src="http://localhost:8083/jeecg-boot/test/jeecgDemo/image"&ndash;&gt;-->
<!--&lt;!&ndash;            />&ndash;&gt;-->
<!--            <div v-else-->
<!--              style="width: 100%;height: 100%;position: relative;padding: 8px;border: 1px solid #d9d9d9;border-radius: 4px;">-->
<!--              <img style="width: 100px" :src="getImgView(text)" preview="1">-->
<!--            </div>-->
<!--&lt;!&ndash;            <img&ndash;&gt;-->
<!--&lt;!&ndash;              v-else&ndash;&gt;-->
<!--&lt;!&ndash;              :src="getImgView(text)"&ndash;&gt;-->
<!--&lt;!&ndash;              :preview="record.id"&ndash;&gt;-->
<!--&lt;!&ndash;              height="25px"&ndash;&gt;-->
<!--&lt;!&ndash;              alt=""&ndash;&gt;-->
<!--&lt;!&ndash;              style="max-width:200px;font-size: 50px;font-style: italic;" />&ndash;&gt;-->
<!--          </template>-->
          <template slot="fileSlot" slot-scope="text">
            <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
            <a-button
              v-else
              :ghost="true"
              type="primary"
              icon="download"
              size="small"
              @click="downloadFile(text)">
              下载
            </a-button>
          </template>

          <span slot="action" slot-scope="text, record">
          <a @click="handleExportXls(record.product+'条码追溯',record)">导出</a>
        </span>
        </a-table>
      </div>

      <a-tabs defaultActiveKey="1" :style="{width:leftWidth,float:'left'}" :activeKey="tabsModel" @change="tabsChange">
        <a-tab-pane tab="产品生产历史" key="1">
          <MesUnitHistoryList :mainId="selectedMainId" :line="line" @itemclick="cpnclick" />
        </a-tab-pane>
        <a-tab-pane tab="不良记录" key="2" forceRender>
          <QisDefectsList :mainId="selectedMainId"></QisDefectsList>
        </a-tab-pane>
        <a-tab-pane tab="零件条码列表" key="3">
          <MesPartBarcodeList :mainId="selectedMainId"></MesPartBarcodeList>
        </a-tab-pane>
        <a-tab-pane tab="原料批次明细" key="4">
          <MesMaterialSetProductList :mainId="selectedMainId" />
        </a-tab-pane>
      </a-tabs>
      <a-tabs defaultActiveKey="1" :style="{width:rightWidth,float:'right'}">
        <a-tab-pane tab="参数明细" key="1">
          <MesProcDataValueList :mainId="procDataMainId" />
        </a-tab-pane>
        <a-tab-pane v-if="isNok" tab="不良明细" key="2" forceRender>
          <MesStatusWordValueList :mainId="procDataMainId" />
        </a-tab-pane>
        <a-tab-pane tab="X-Ray" key="3">

          <img style="width: 70%;height: 70%" :src="getImgView('http://192.168.1.241:8083/jeecg-boot/test/jeecgDemo/image.png')" preview="1">
        </a-tab-pane>
      </a-tabs>
      <quality-rework-modal ref="modalForm" @close="modalFormClose"></quality-rework-modal>
      <quality-abnormal-modal ref="modalForm2" @close="modalFormClose"></quality-abnormal-modal>
      <j-modal
        title="确认"
        :visible="visible"
        :confirmLoading="confirmLoading"
        switchFullscreen
        @ok="handleOk"
        @cancel="handleCancel"
        cancelText="关闭">
        <a-spin :spinning="confirmLoading">
          <a-form-model ref="form" :model="syncModel">
                  <j-search-select-tag placeholder="请选择产线/产线组" v-model="syncModel.line"
                                       dict="mes_line_cfg,line,line" />
          </a-form-model>
        </a-spin>
      </j-modal>
    </a-card>
  </keep-alive>
</template>

<script>

import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { downFile, getAction, httpAction } from '@/api/manage'
import MesUnitHistoryList from './modules/MesUnitHistoryList.vue'
import MesMaterialSetProductList from './modules/MesMaterialSetProductList.vue'
import MesProcDataValueList from './modules/MesProcDataValueList.vue'
import MesStatusWordValueList from './modules/MesStatusWordValueList.vue'
import QisDefectsList from './modules/QisDefectsList.vue'
import MesPartBarcodeList from './modules/MesPartBarcodeList.vue'
import MesUnitidList from './modules/MesUnitidList.vue'
import QualityReworkModal from './modules/QualityReworkModal.vue'
import QualityAbnormalModal from './modules/QualityAbnormalModal.vue'
import '@/assets/less/TableExpand.less'
import Vue from 'vue'
import { USER_INFO } from '@/store/mutation-types'
import ShiftSelect from '@comp/mes/ShiftSelect.vue'
import OpSelect from '@comp/mes/OpSelect.vue'

export default {
  barcode: '',
  name: 'BarcodeTrace',
  mixins: [JeecgListMixin],
  components: {
    OpSelect, ShiftSelect,
    MesUnitHistoryList,
    MesUnitidList,
    QisDefectsList,
    MesProcDataValueList,
    MesStatusWordValueList,
    QualityReworkModal,
    QualityAbnormalModal,
    MesPartBarcodeList,
    MesMaterialSetProductList
  },
  data() {
    return {
      description: '序列号列表管理页面',
      // 表头
      queryParam: {
        unitsn: this.$route.query.unitsn
      },
      visible:false,
      confirmLoading:false,
      isAbnormal: false,
      isNok: false,
      oneLoad: 1,
      leftWidth: '65%',
      rightWidth: '35%',
      syncModel:{},
      columns: [
        {
          title: '工单ID',
          align: 'center',
          dataIndex: 'woid'
        },
        {
          title: '序列号',
          align: 'center',
          dataIndex: 'unitsn'
        },
        {
          title: '产品码',
          align: 'center',
          dataIndex: 'product'
        },
        {
          title: '产品或产品组',
          align: 'center',
          dataIndex: 'partno'
        },
        {
          title: '产线或产线组',
          align: 'center',
          dataIndex: 'line'
        },
        {
          title: '工位',
          align: 'center',
          dataIndex: 'op'
        },
        {
          title: '工站',
          align: 'center',
          dataIndex: 'stn'
        },
        {
          title: '盒号',
          align: 'center',
          dataIndex: 'lotno',
          scopedSlots: { customRender: 'lotno' }
        },
        {
          title: '箱号',
          align: 'center',
          dataIndex: 'boxCode',
          scopedSlots: { customRender: 'boxCode' }
        },
        {
          title: '日期',
          align: 'center',
          dataIndex: 'dt',
          customRender: function(text) {
            return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
          }
        },
        {
          title: '结果',
          align: 'center',
          dataIndex: 'result_dictText'
        },
        {
          title: 'X-Ray',
          align: 'center',
          dataIndex: 'xray',
          scopedSlots: { customRender: 'imgSlot' }
        },
        {
          title: '重复加工次数',
          align: 'center',
          dataIndex: 'repeatCount'
        },
        {
          title: '状态',
          align: 'center',
          dataIndex: 'status_dictText'
        },
        {
          title: '班次日期',
          align: 'center',
          dataIndex: 'shiftDate',
          customRender: function(text) {
            return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
          }
        },
        {
          title: '班次',
          align: 'center',
          dataIndex: 'shift'
        },
        {
          title: '产线类型',
          align: 'center',
          dataIndex: 'segmentCode_dictText'
        },
        {
          title: '更新时间',
          align: 'center',
          dataIndex: 'ctime'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' }
        }
      ],
      runCmd: '/monitor/api/runCmd',
      url: {
        list: '/trace/barcodeTrace/queryByCode',
        exportXlsUrl: '/trace/barcodeTrace/exportXls'
      },
      dictOptions: {},
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 5,
        pageSizeOptions: ['5', '10', '50'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      selectedMainId: '',
      line: '',
      procDataMainId: '',
      tabsModel: '1',
      lastDate: new Date(),
      timeOut: 100,
      barcode: '',
      firstCode: '',
      superFieldList: []
    }
  },
  created() {
    // this.getSuperFieldList()
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }
  },
  methods: {
    modalFormClose() {
      console.log('关闭弹窗')
      this.loadData(1)
    },
    openRelease() {
      const that = this
      //判断产品当前状态
      let product = this.selectionRows[0]
      if (!product) {
        this.$message.warning('请选择一条数据！')
        return
      }
      if (product.status === '5' || product.status === '6') {
        this.load = {
          serviceid: 'mes',
          cmd: 'Release',
          entityid: product.unitsn,
          clientid: that.line,
          user: Vue.ls.get(USER_INFO).username,
          Single: '1'
        }
        that.confirmLoading = true
        httpAction(this.runCmd, this.load, 'post').then((res) => {
          if (res.success) {
            if (res.result.errorCode === 'OK') {
              that.$message.success('操作成功！')
            }
          } else {
          }
        }).finally(() => {
          that.confirmLoading = false
          that.close()

        })
      } else {
        this.$message.warning('当前产品状态无需恢复！')
        return
      }
    },
    handleOk(){
      const that = this
      let unitsn = ''
      if (this.queryParam.unitsn){
        unitsn = this.queryParam.unitsn
      }else{
        unitsn = this.selectionRows[0].unitsn
      }
      this.load = {
        serviceid: 'mes',
        cmd: 'getunitsn',
        entityid: unitsn,
        clientid: this.syncModel.line,
      }
      that.confirmLoading = true
      httpAction(this.runCmd, this.load, 'post').then((res) => {
        if (res.success) {
          if (res.result.errorCode === 'OK') {
            that.$message.success('同步成功！')
            this.visible = true
          }
        } else {
        }
      }).finally(() => {
        that.confirmLoading = false
      })
    },
    handleCancel() {
      this.syncModel={}
      this.visible = false
    },
    openDataSync(){
      this.syncModel={}
      this.visible = true
    },
    openAbnormal() {
      this.$refs.modalForm2.open(this.queryParam.unitsn)
    },
    openRework() {
      console.log(this.selectionRows)
      if (this.selectionRows.length === 0) {
        this.$message.warning('请选择一条数据！')
        return
      }
      //打开返工弹窗传入产线编号
      this.$refs.modalForm.open(this.selectionRows[0])
    },
    clickLotNo(val) {
      this.$router.push({ path: './MesLotStatusList', query: { lotNo: val } })
    },
    handleExportXls(fileName, record) {
      if (!fileName || typeof fileName !== 'string') {
        fileName = '导出文件'
      }
      let param = this.getQueryParams()
      if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
        param['selections'] = this.selectedRowKeys.join(',')
      }
      console.log('导出参数', param)
      downFile(this.url.exportXlsUrl, record).then((data) => {
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xlsx')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) // 下载完成移除元素
          window.URL.revokeObjectURL(url) // 释放掉blob对象
        }
      })
    },
    initDictConfig() {
    },
    searchQuery() {
      //判断输入框内如果有内容 清楚掉展示缓存的
      //判断是否是完整条码信息
      if (this.queryParam.unitsn.split(';').length > 1) {
        let arr = this.queryParam.unitsn.split(';')
        this.queryParam.unitsn = arr[arr.length - 2]
      } else if (this.queryParam.unitsn.split('  ').length > 1) {
        let arr = this.queryParam.unitsn.split('  ')
        this.queryParam.unitsn = arr[arr.length - 2]
      } else {
      }
      this.loadData(1)
    },
    clickThenSelect(record) {
      return {
        on: {
          click: () => {
            this.onSelectChange(record.federationId.split(','), [record])
          }
        }
      }
    },
    onClearSelected() {
      this.selectedRowKeys = []
      this.selectionRows = []
      this.selectedMainId = ''
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      console.log(selectedRowKeys)
      console.log(selectionRows)
      this.line = selectionRows[0].line
      this.selectedMainId = selectionRows[0].unitsn
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      // 加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      this.onClearSelected()
      var params = this.getQueryParams()// 查询条件

      if (this.oneLoad === 1) {
        this.oneLoad = 2
      } else {
        this.loading = true
        getAction(this.url.list, params).then((res) => {
          if (res.success) {
            this.dataSource = res.result.records
            this.ipagination.total = res.result.total
            if (res.result.records.length > 0) {
              this.onSelectChange([this.dataSource[0].federationId], [this.dataSource[0]])
              this.queryParam.unitsn = ''
              this.isAbnormal = false
            } else {
              this.isAbnormal = true
            }
          }
          if (res.code === 510) {
            this.$message.warning(res.message)
          }
        }).finally(() => {
          this.loading = false
        })
      }
    },
    tabsChange(key) {
      this.tabsModel = key
      if (key === '1') {
        this.leftWidth = '65%'
        this.rightWidth = '35%'
      } else {
        this.leftWidth = '100%'
        this.rightWidth = '0%'
      }
    },
    cpnclick(item) {
      this.procDataMainId = item.recId
      if (item.result === '2') {
        this.isNok = true
      } else {
        this.isNok = false
      }
    },
    getSuperFieldList() {
      let fieldList = []
      fieldList.push({ type: 'string', value: 'woid', text: '工单ID', dictCode: '' })
      fieldList.push({ type: 'string', value: 'unitsn', text: '序列号', dictCode: '' })
      fieldList.push({ type: 'string', value: 'partno', text: '产品或产品组', dictCode: '' })
      fieldList.push({ type: 'string', value: 'line', text: '产线或产线组', dictCode: '' })
      fieldList.push({ type: 'string', value: 'op', text: '工位', dictCode: '' })
      fieldList.push({ type: 'string', value: 'stn', text: '工站', dictCode: '' })
      fieldList.push({ type: 'date', value: 'dt', text: '日期' })
      fieldList.push({ type: 'string', value: 'result', text: '9=Default,0=Loaded,1=OK,2=NOK', dictCode: '' })
      fieldList.push({ type: 'BigDecimal', value: 'repeatCount', text: '重复加工次数', dictCode: '' })
      fieldList.push({
        type: 'string',
        value: 'status',
        text: '0: Init, 1: WIP, 2: FG, 3: Rework, 5: Scrap, 6:On Hold,7: InterFG,8: CheckPart',
        dictCode: ''
      })
      fieldList.push({ type: 'date', value: 'shiftDate', text: '班次日期' })
      fieldList.push({ type: 'string', value: 'shift', text: '班次', dictCode: '' })
      fieldList.push({ type: 'string', value: 'rwktoOp', text: '返工至工位', dictCode: '' })
      fieldList.push({ type: 'string', value: 'rwktoStn', text: '返工至工站', dictCode: '' })
      fieldList.push({ type: 'BigDecimal', value: 'cycleId', text: '运行周期ID', dictCode: '' })
      fieldList.push({ type: 'BigDecimal', value: 'parttypeid', text: '产品ID', dictCode: '' })
      fieldList.push({ type: 'BigDecimal', value: 'statusword', text: '状态字', dictCode: '' })
      fieldList.push({ type: 'string', value: 'segmentCode', text: '0:主线  1:1号支线 2:2号支线', dictCode: '' })
      fieldList.push({ type: 'string', value: 'rwkCode', text: '返工代码', dictCode: '' })
      fieldList.push({ type: 'string', value: 'lotno', text: '是否成批', dictCode: '' })
      fieldList.push({ type: 'date', value: 'ctime', text: '更新时间' })
      this.superFieldList = fieldList
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
